package com.ctshk.rpc.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.*;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.system.dto.QueryBigClientAndAgentDTO;
import com.ctshk.rpc.system.dto.SysBigClientDTO;
import com.ctshk.rpc.system.dto.SysBigClientQueryListDTO;
import com.ctshk.rpc.system.entity.SysAgent;
import com.ctshk.rpc.system.entity.SysBigClient;
import com.ctshk.rpc.system.mapper.SysAgentMapper;
import com.ctshk.rpc.system.mapper.SysBigClientMapper;
import com.ctshk.rpc.system.req.SysBigClientAddReq;
import com.ctshk.rpc.system.req.SysBigClientApprovalReq;
import com.ctshk.rpc.system.req.SysBigClientQueryListReq;
import com.ctshk.rpc.system.req.SysBigClientUpdateStatusReq;
import com.ctshk.rpc.system.service.ISysBigClientService;
import com.ctshk.rpc.workflow.dto.ApprovalCheckDTO;
import com.ctshk.rpc.workflow.dto.ApprovalStartDTO;
import com.ctshk.rpc.workflow.service.ISysApprovalService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 大客户 服务实现类
 * </p>
 *
 * @author 张志朋
 * @since 2021-02-03
 */
@Slf4j
@DubboService
public class SysBigClientServiceImpl extends ServiceImpl<SysBigClientMapper, SysBigClient> implements ISysBigClientService {

    @DubboReference
    private ISysApprovalService sysApprovalService;

    @Autowired
    private SysPermissionServiceImpl sysPermissionService;

    @Autowired
    private SysAgentMapper sysAgentMapper;

    /**
     * 新增大客户
     *
     * @param req    新增大客户入参
     * @param userId 当前登录人id
     */
    @Override
    public Result add(SysBigClientAddReq req, Long userId, int addType) {
        // 查重大客户中英文名
        QueryWrapper<SysBigClient> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysBigClient::getCnName, req.getCnName()).or();
        queryWrapper.lambda().eq(SysBigClient::getEnName, req.getEnName());
        List<SysBigClient> bigClients = baseMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(bigClients)) {
            throw new BusinessException(SystemError.BIG_CLIENBIG_CLIENT_6001T_6002);
        }
        // 查重系统编码
        QueryWrapper<SysBigClient> codeQueryWrapper = new QueryWrapper<>();
        codeQueryWrapper.lambda().eq(SysBigClient::getFinanceSysCode, req.getFinanceSysCode());
        if (CollectionUtils.isNotEmpty(baseMapper.selectList(codeQueryWrapper))) {
            throw new BusinessException(SystemError.BIG_CLIENBIG_CLIENT_6001T_6005);
        }

        SysBigClient bigClient = EntityUtil.copy(req, SysBigClient.class);
        Long nextId = SnowflakeIdWorker.nextId();
        bigClient.setId(nextId);
        bigClient.setCreateId(userId);
        bigClient.setGmtCreate(LocalDateTime.now());


        //走审批流程
        if (addType == 2) {
            Result<ApprovalStartDTO> approvalResult = sysApprovalService.start(SystemBusinessType.RESOURCES.getCode(),
                    SysApprovalType.ADDCLIENT_SYSTEM.getCode(), nextId,
                    userId, null, null);
            if (!approvalResult.isSuccess()) {
                log.error(approvalResult.getMsg());
//                throw new BusinessException(SystemError.SYS_500);
                return approvalResult;
            }
            bigClient.setCheckStatus(BigClientCheckStatus.REVIEW.getCode());
            bigClient.setStatus(SupplierStatus.DISABLE.getCode());
        }
        //仅保存
        if (addType == 1) {
            bigClient.setCheckStatus(BigClientCheckStatus.SAVED.getCode());
            bigClient.setStatus(SupplierStatus.DISABLE.getCode());
        }


        baseMapper.insert(bigClient);
        return Result.success();
    }

    /**
     * 大客户详情
     *
     * @param id 大客户id
     * @return 大客户详情
     */
    @Override
    public Result<SysBigClientDTO> query(Long id) {
        SysBigClient sysBigClient = baseMapper.selectById(id);
        if (null == sysBigClient) {
            return Result.failed(SystemError.BIG_CLIENT_6001);
        }
        SysBigClientDTO bigClientDTO = EntityUtil.copy(sysBigClient, SysBigClientDTO.class);
        return Result.success(bigClientDTO);
    }

    /**
     * 编辑大客户
     *
     * @param req     编辑大客户入参
     * @param userId  当前登录人id
     * @param addType 1仅保存,2走审批流程
     * @return
     */
    @Override
    public Result editBigClient(SysBigClientAddReq req, Long userId, int addType) {
        Long clientId = req.getId();
        SysBigClient oldClient = baseMapper.selectById(clientId);
        String newCnName = req.getCnName();
        String newEnName = req.getEnName();
        if (!newCnName.equals(oldClient.getCnName()) || !newEnName.equals(oldClient.getEnName())) {
            // 查重中英文名
            QueryWrapper<SysBigClient> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .and(e->e.eq(SysBigClient::getCnName, newCnName)
                            .or().eq(SysBigClient::getEnName, newEnName))
                    .ne(SysBigClient::getId, clientId);
            if (CollectionUtils.isNotEmpty(baseMapper.selectList(queryWrapper))) {
                throw new BusinessException(SystemError.BIG_CLIENBIG_CLIENT_6001T_6002);
            }
        }


        SysBigClient bigClient = EntityUtil.copy(req, SysBigClient.class);
        bigClient.setModifiedId(userId);
        bigClient.setGmtModified(LocalDateTime.now());


        //走审批流程
        if (addType == 2) {
            Result<ApprovalStartDTO> approvalResult = sysApprovalService.start(SystemBusinessType.RESOURCES.getCode(),
                    SysApprovalType.ADDCLIENT_SYSTEM.getCode(), clientId,
                    userId, null, null);
            if (!approvalResult.isSuccess()) {
                log.error(approvalResult.getMsg());
//                throw new BusinessException(SystemError.SYS_500);
                return approvalResult;
            }
            bigClient.setCheckStatus(BigClientCheckStatus.REVIEW.getCode());
            bigClient.setStatus(SupplierStatus.DISABLE.getCode());
        }
        //仅保存
        if (addType == 1) {
            bigClient.setCheckStatus(BigClientCheckStatus.SAVED.getCode());
            bigClient.setStatus(SupplierStatus.DISABLE.getCode());
        }

        int update = baseMapper.updateById(bigClient);
        if (update < 1) {
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(req.getId());

    }


    /**
     * 大客户管理列表查询
     *
     * @param req 入参
     * @return 返回列表
     */
    @Override
    public PageResponse<SysBigClientQueryListDTO> queryList(SysBigClientQueryListReq req, TokenUser tokenUser) {
        IPage<SysBigClientQueryListDTO> page = new Page<>(req.getPageNo(), req.getPageSize());
        page = baseMapper.queryList(req, page);
        PageResponse<SysBigClientQueryListDTO> result = new PageResponse<>(page.getRecords(), page.getCurrent() == 1,
                page.getTotal() <= (page.getCurrent() * page.getSize()),
                page.getTotal(), page.getCurrent(), page.getSize());
        return result;
    }

    /**
     * 大客户管理列表查询(验证)
     *
     * @param req 入参
     * @return 返回列表
     */
    @Override
    public PageResponse<SysBigClientQueryListDTO> queryListPer(SysBigClientQueryListReq req, TokenUser tokenUser) {
        Result<List<Long>> permissionResult = sysPermissionService.queryPermission(req.getMenuId(), tokenUser.getId());
        if (!permissionResult.isSuccess()) {
            SystemError result = SystemError.getDefined(permissionResult.getCode());
            throw new BusinessException(result);
        }
        //不是管理员
        if (!GlobalConstants.Role.isAdmin(tokenUser.getUsername())) {
            req.setIsNotAdmin(1);
            req.setUserIds(permissionResult.getData());
        }
        IPage<SysBigClientQueryListDTO> page = new Page<>(req.getPageNo(), req.getPageSize());
        page = baseMapper.queryList(req, page);
        PageResponse<SysBigClientQueryListDTO> result = new PageResponse<>(page.getRecords(), page.getCurrent() == 1,
                page.getTotal() <= (page.getCurrent() * page.getSize()),
                page.getTotal(), page.getCurrent(), page.getSize());
        return result;
    }

    @Override
    public List<QueryBigClientAndAgentDTO> queryBigClientAndAgent(String name) {
        List<QueryBigClientAndAgentDTO> result = new ArrayList<>();
        //大客户
        QueryWrapper<SysBigClient> sbc = new QueryWrapper<>();
        sbc.lambda().eq(SysBigClient::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(SysBigClient::getCheckStatus, SupplierAddCheckStatus.REVIEW_YES.getCode())
                .eq(SysBigClient::getStatus, SupplierStatus.ENABLE.getCode())
                .like(StringUtils.isNotBlank(name), SysBigClient::getCnName, name);
        List<SysBigClient> sysBigClients = baseMapper.selectList(sbc);
        if (sysBigClients != null && sysBigClients.size() > 0) {
            QueryBigClientAndAgentDTO qbcaa = new QueryBigClientAndAgentDTO();
            sysBigClients.forEach(e -> {
                qbcaa.setId(e.getId());
                qbcaa.setCnName(e.getCnName());
                qbcaa.setType(1);//临时类型大客户
                result.add(qbcaa);
            });
        }
        //代理商
        QueryWrapper<SysAgent> sa = new QueryWrapper<>();
        sa.lambda().eq(SysAgent::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(SysAgent::getCheckStatus, SupplierAddCheckStatus.REVIEW_YES.getCode())
                .eq(SysAgent::getStatus, SupplierStatus.ENABLE.getCode())
                .like(StringUtils.isNotBlank(name), SysAgent::getCnName, name);
        List<SysAgent> sysAgents = sysAgentMapper.selectList(sa);
        if (sysAgents != null && sysAgents.size() > 0) {
            QueryBigClientAndAgentDTO qbcaa = new QueryBigClientAndAgentDTO();
            sysAgents.forEach(e -> {
                qbcaa.setId(e.getId());
                qbcaa.setCnName(e.getCnName());
                qbcaa.setType(2);//临时类型代理商
                result.add(qbcaa);
            });
        }
        return result;
    }

    @Override
    public Result approval(SysBigClientApprovalReq req) {

        if (req.getApprovalId() == null) {
            return Result.failed(SystemError.SYS_402);
        }
        if (!ApprovalStatus.isCheckStatus(req.getApprovalStatus())) {
            return Result.failed(SystemError.SYS_402);
        }

        //查询大客户信息
        QueryWrapper<SysBigClient> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysBigClient::getId, req.getBusinessId());
        queryWrapper.lambda().eq(SysBigClient::getIsDeleted, IsDeletedCode.NO);
        SysBigClient bigClient = baseMapper.selectOne(queryWrapper);
        if (bigClient == null) {
            return Result.failed(SystemError.SYS_411);
        }

        /**
         * 审批
         */
        Result<ApprovalCheckDTO> result = sysApprovalService.check(req.getApprovalId(), req.getUserId(),
                req.getApprovalStatus(), req.getRemark());
        if (!result.isSuccess()) {
            SystemError systemError = SystemError.getDefined(result.getCode());
            return Result.failed(systemError);
        }
        if (result.getData() == null || !result.getData().getIsFinish()) {
            return Result.success();
        }

        //审批状态（0：撤回，4：审批不通过，3：审批通过）
        if (req.getApprovalStatus() == SupplierAddCheckStatus.REVIEW_YES.getCode()) {
            //审批通过
            bigClient.setCheckStatus(BigClientCheckStatus.REVIEW_YES.getCode());
            bigClient.setStatus(SupplierStatus.ENABLE.getCode());

        } else if (req.getApprovalStatus() == SupplierAddCheckStatus.REVIEW_NO.getCode()) {
            //审批不通过
            bigClient.setCheckStatus(BigClientCheckStatus.REVIEW_NO.getCode());
            bigClient.setStatus(SupplierStatus.DISABLE.getCode());
        } else {
            //撤回
            bigClient.setCheckStatus(BigClientCheckStatus.SAVED.getCode());//已保存
            bigClient.setStatus(SupplierStatus.DISABLE.getCode());
        }


        LocalDateTime nowLocalDateTime = LocalDateTime.now();
        bigClient.setModifiedId(req.getUserId());
        bigClient.setGmtModified(nowLocalDateTime);
        baseMapper.updateById(bigClient);
        return Result.success();

    }

    @Override
    public Result updateStatus(SysBigClientUpdateStatusReq req) {
        SysBigClient bigClient = baseMapper.selectById(req.getId());
        if (bigClient == null) {
            throw new BusinessException(SystemError.SYS_411);
        }
        //如果改为有效状态
        if (req.getNewStatus() == SupplierStatus.ENABLE.getCode()) {
            //审批状态不是审批通过的其他状态下不能修改为有效状态
            if (bigClient.getCheckStatus() != BigClientCheckStatus.REVIEW_YES.getCode()) {
                throw new BusinessException(SystemError.BIG_CLIENBIG_CLIENT_6001T_6006);
            }
        }

        bigClient.setStatus(req.getNewStatus());
        LocalDateTime nowLocalDateTime = LocalDateTime.now();
        bigClient.setModifiedId(req.getUserId());
        bigClient.setGmtModified(nowLocalDateTime);
        baseMapper.updateById(bigClient);
        return Result.success();
    }

    @Override
    public Result deleteById(Long id) {
        return baseMapper.deleteById(id) > 0 ? Result.success() : Result.failed(SystemError.CMS_23001);
    }

}
